/*
* @Author: Administrator
* @Date:   2018-01-06 10:54:33
* @Last Modified by:   Administrator
* @Last Modified time: 2018-01-08 14:19:40
*/
const router = require('express').Router()
const axios = require('axios')
const qs = require('qs')

const url = 'http://jhmaimai.top/react_wp/wp-json/jwt-auth/v1/token'
const login = (param) => {
  const res = axios({
    method: 'POST',
    url: url,
    data: param
  })
  return res
}
router.post('/login', function (req, res) {
  login(qs.stringify(req.body))
    .then((result) => {
      if (result.status === 200) {
        req.session.userInfo = result.data
        req.session.userToken = result.data.token
        delete result.data.token
        res.json(result.data)
      }
    })
    .catch(err => {
      if (err.response) {
        res.json({
          code: 0,
          message: '登录失败,请检查用户名和密吗或者稍后重试...'
        })
      }
    })
})
router.post('/logout', function (req, res) {
  req.session.userInfo = {}
  res.json({
    code: 1,
    message: '退出成功'
  })
})
router.post('/regist', function (req, res) {
  const registUrl = 'http://jhmaimai.top/react_wp/wp-json/wp/v2/users'
  const param = {
    username: 'baijiwei66',
    password: 'baijiwei7419428'
  }
  login(param).then(result => {
    if (result.status === 200 && result.data.token) {
      axios({
        method: 'POST',
        url: registUrl,
        data: qs.stringify(req.body),
        headers: {
          Authorization: 'Bearer ' + result.data.token
        }
      })
        .then((rlt) => {
          if (rlt.status === 200 || rlt.status === 201) {
            res.json({
              code: 1,
              message: '注册成功'
            })
          }
        })
        .catch(err => {
          if (err.response) {
            res.json({
              code: 0,
              message: err.message
            })
          }
        })
    }
  })
})
module.exports = router
